package felix.things.router.mqtt.server.store.starter;

import felix.things.router.mqtt.server.store.kafka.SimplePartitioner;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.common.serialization.StringSerializer;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.kafka.core.DefaultKafkaProducerFactory;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.core.ProducerFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Felix
 * @date 2020/6/14
 */
@Configurable
public class StoreStarter {
    @Value("${kafka.producer.broker-enabled:false}")
    private boolean brokerEnabled;

    @Value("${kafka.producer.bootstrap-servers:127.0.0.1:9092}")
    private String bootstrapServices;

    @Value("${kafka.producer.retries:0}")
    private int retries;

    @Value("${kafka.producer.ack:all}")
    private String ack;

    @Value("${kafka.producer.batch-size:16384}")
    private int batchSize;

    @Value("${kafka.producer.linger-ms:1}")
    private int lingerMs;

    @Value("${kafka.producer.buffer-memory:67108864}")
    private long bufferMemory;

    private Map<String, Object> producerConfigs() {
        Map<String, Object> props = new HashMap<>();
        props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServices);
        props.put(ProducerConfig.RETRIES_CONFIG, retries);
        props.put(ProducerConfig.ACKS_CONFIG, ack);
        props.put(ProducerConfig.BATCH_SIZE_CONFIG, batchSize);
        props.put(ProducerConfig.LINGER_MS_CONFIG, lingerMs);
        props.put(ProducerConfig.BUFFER_MEMORY_CONFIG, bufferMemory);
        props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
        props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
        props.put(ProducerConfig.PARTITIONER_CLASS_CONFIG, SimplePartitioner.class);
        return props;
    }

    private ProducerFactory<String, String> producerFactory() {
        return new DefaultKafkaProducerFactory<>(producerConfigs());
    }

    @Bean
    public KafkaTemplate<String, String> kafkaTemplate() {
        if (brokerEnabled) {
            return new KafkaTemplate<>(producerFactory());
        } else {
            return null;
        }
    }
}
